//
//  ReadingViewController.m
//  电子书阅览器
//
//  Created by apple on 16/12/12.
//  Copyright © 2016年 LWB. All rights reserved.
//
#define margin 5
#import "ReadingViewController.h"

@interface ReadingViewController ()<UITextViewDelegate>
@property (nonatomic,strong)UITextView *content;
//全文
@property(nonatomic,copy)NSString* fullText;
@property(nonatomic,assign)int allPage;
@property(nonatomic,assign)int currentPage;
@property(nonatomic,strong)UIToolbar *toolBar;
@property(nonatomic,strong)UIView *toolView;
@property(nonatomic,strong)UILabel *sliderLabel;
@property(nonatomic,strong)UIView *multiFunctionView;
@property(nonatomic,assign)CGFloat lengthPerPage;
@property(nonatomic,assign)CGFloat totalHeight;
@end

@implementation ReadingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//   //处理显示一页文字的uiview
//    [UIView beginAnimations:nil context:nil];
//    //页面的跳转的间隔时间
//    [UIView setAnimationDuration:0.5f];
//    //页面动画执行
//    [UIView commitAnimations];
    UIImage *image =[UIImage imageNamed:@"bg6"];
    self.view.backgroundColor =[UIColor colorWithPatternImage:[[UIImage imageNamed:@"bg6"] stretchableImageWithLeftCapWidth:image.size.width*0.5 topCapHeight:image.size.height*0.54]];
    [self setNavigation];
    [self setUpTextView];
    [self setUpToolView];
    [self setUpSlider];
    [self setUpToolBar];
    [self tapGesture];
    NSString *st =[NSString stringWithString:_content.text];
    NSLog(@"st%@",st);
    [self swipeGesture];
    [self setUpmultiFunctionView];
   
    // Do any additional setup after loading the view.
}
-(NSInteger)calculateHeight:(CGFloat )textHeigt fontSzie:(NSUInteger )fontSi{
//    CGRect rect = [self.fullText boundingRectWithSize:CGSizeMake(self.view.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[[UILabel new].font fontWithSize:fontSi]} context:nil];
//    _totalHeight = ceil(rect.size.height);
//    NSLog(@"%f",_totalHeight);
//    _allPage = ceil(_totalHeight / (self.view.frame.size.height-17));
//    _lengthPerPage =_fullText.length/_allPage;
//    
////    if (_lengthPerPage<textHeigt) {
////        return _lengthPerPage;
////    }else{
        NSRange range;
        for (NSInteger i=0; i<self.fullText.length;i++) {
            range  =NSMakeRange(0, i);
            NSString *str = [_fullText substringWithRange:range];
            NSLog(@"%@",str);
             CGRect rect1 = [str boundingRectWithSize:CGSizeMake(self.view.frame.size.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[[UILabel new].font fontWithSize:fontSi]} context:nil];
            if (rect1.size.height>textHeigt) {
                return i--;
               // NSLog(@"%f,%f",rect1.size.height,textHeigt);
            }
             NSLog(@"-->%lf,%lf,%ld,%f",rect1.size.height,textHeigt,i,_lengthPerPage);
        }
    return _lengthPerPage;
}
-(void)setUpmultiFunctionView{
    _multiFunctionView = [[UIView alloc]initWithFrame:CGRectMake(self.view.frame.size.width,65, 60, 75)];
    UIImageView *imgeView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"SenderTextNodeBkg"]];
    imgeView.transform = CGAffineTransformMakeRotation(-M_PI_2);
    _multiFunctionView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_multiFunctionView];
    UITableView *tbView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,120,_lengthPerPage) style:UITableViewStylePlain];
    tbView.backgroundColor = [UIColor redColor];
    tbView.backgroundView = imgeView;
    [_multiFunctionView addSubview:tbView];
}
-(void)setNavigation{
    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];
    self.navigationController.navigationBarHidden = YES;
        UIBarButtonItem  *backToCell = [[UIBarButtonItem alloc]initWithTitle:@"返回书架" style:UIBarButtonItemStylePlain target:self action:@selector(backToCell)];
    self.navigationItem.leftBarButtonItem =backToCell;
    UIBarButtonItem  *multiFunction = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"navigationbar_more_highlighted"] style:UIBarButtonItemStylePlain target:self action:@selector(multiFunction)];
    self.navigationItem.rightBarButtonItem = multiFunction;
    
}
-(void)multiFunction{
    if (_multiFunctionView.frame.origin.x==self.view.frame.size.width) {
        [UIView animateWithDuration:0.6 animations:^{
//            _multiFunctionView.transform = CGAffineTransformMakeScale(1, 1);
            _multiFunctionView.transform =CGAffineTransformTranslate(_multiFunctionView.transform,-130, 0);
            NSLog(@"%f,%f,%f,%f",_multiFunctionView.frame.origin.x,_multiFunctionView.frame.origin.y,_multiFunctionView.frame.size.width,_multiFunctionView.frame.size.height);
        }];
    }else{
        [UIView animateWithDuration:0.6 animations:^{
//            _multiFunctionView.transform = CGAffineTransformMakeScale(0.5, 0.5);
            _multiFunctionView.transform =CGAffineTransformTranslate(_multiFunctionView.transform,130, 0);
             NSLog(@"%f,%f,%f,%f",_multiFunctionView.frame.origin.x,_multiFunctionView.frame.origin.y,_multiFunctionView.frame.size.width,_multiFunctionView.frame.size.height);
        }];
    }
}
-(void)setUpSlider{
    _sliderLabel = [[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width-60)/2, 5, 60, 15)];
    _sliderLabel.text =[NSString stringWithFormat:@"%d/%d",_currentPage,_allPage];
    [_toolView addSubview:_sliderLabel];
    UISlider *slider = [[UISlider alloc]initWithFrame:CGRectMake(30, 25, self.view.frame.size.width-60, 30)];
    slider.maximumValue = _allPage;
    slider.minimumValue =1;
    slider.value =_currentPage;
    [slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [_toolView addSubview:slider];
}
-(void)sliderAction:(UISlider *)slider{
    _currentPage = slider.value;
    [UIView animateWithDuration:0.5 animations:^{
    [_content setContentOffset:CGPointMake(0, (_currentPage-1)*_content.frame.size.height) animated:YES];
        _sliderLabel.text =[NSString stringWithFormat:@"%d/%d",_currentPage,_allPage];
    }];
}
-(void)setUpToolView{
    _toolView =[[UIView alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height, self.view.frame.size.width, 120)];
    _toolView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_toolView];
}
-(void)tapGesture{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAtion:)];
    tap.numberOfTouchesRequired = 1;
    tap.numberOfTapsRequired = 1;
    [self.view addGestureRecognizer:tap];
}
-(void)tapAtion:(UITapGestureRecognizer *)tap{
    if (self.navigationController.navigationBarHidden == YES) {
        [UIView animateWithDuration:0.8 animations:^{
            self.navigationController.navigationBarHidden = NO;
            _toolView.transform =CGAffineTransformTranslate(_toolView.transform, 0,-120);
            NSLog(@"%f",_toolView.frame.origin.y);
        }];
    }else{
        [UIView animateWithDuration:0.8 animations:^{
            self.navigationController.navigationBarHidden = YES;
           _toolView.transform =CGAffineTransformTranslate(_toolView.transform, 0,120);
          //  NSLog(@"")

        }];
   }
}
-(NSString *)fullText{
    if (_fullText==nil) {
        NSError *err;
        _fullText = [NSString stringWithContentsOfFile:[NSString stringWithFormat:@"/Users/apple/Desktop/IOS/电子书阅览器/电子书阅览器/%@.txt",_flag] encoding:NSUTF8StringEncoding error:&err];
        if (err!=nil) {
            NSLog(@"%@",err);
        }
    }
    return _fullText;
}
-(void)setUpTextView{
   // UILabel *lable =
    _content = [[UITextView alloc]initWithFrame:CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height-17)];
    _content.font = [UIFont systemFontOfSize:17];
    _content.textColor = [UIColor blackColor];
    //设置当前页数为1
    _currentPage = 0;
_lengthPerPage =[self calculateHeight:_content.frame.size.height fontSzie:17];
    NSLog(@"%f",_lengthPerPage);
    
    _allPage =_fullText.length/_lengthPerPage;
    _content.backgroundColor = [UIColor clearColor];
//    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
//    paragraphStyle.lineSpacing = 0;// 字体的行间距
//    
//    NSDictionary *attributes = @{
//                                 NSFontAttributeName:[UIFont systemFontOfSize:17],
//                                 NSParagraphStyleAttributeName:paragraphStyle
//                                 };
//    _content.attributedText = [[NSAttributedString alloc] initWithString:[_fullText substringWithRange:NSMakeRange(_currentPage * _lengthPerPage, _lengthPerPage)] attributes:attributes];
    //_content.text =[_fullText substringWithRange:NSMakeRange(_currentPage * _lengthPerPage, _lengthPerPage)];

   _content.scrollEnabled = NO;
    _content.editable = NO;
    _content.pagingEnabled = YES;
    UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
    //设置轻扫的方向
    swipeGesture.direction = UISwipeGestureRecognizerDirectionRight; //向右
    [_content addGestureRecognizer:swipeGesture];
    UISwipeGestureRecognizer *swipeGestureLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
    //设置轻扫的方向
    swipeGestureLeft.direction = UISwipeGestureRecognizerDirectionUp;
    [_content addGestureRecognizer:swipeGestureLeft];
    UISwipeGestureRecognizer *swipeGestureLeft1 = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeGesture:)];
    //设置轻扫的方向
    swipeGestureLeft.direction =  UISwipeGestureRecognizerDirectionDown;
   // [_content addGestureRecognizer:swipeGestureLeft1];
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGesture:)];
   // [_content addGestureRecognizer:panGesture];

    //轻扫手势触发方法
    [self.view addSubview:_content];
}
-(void)panGesture:(UIPanGestureRecognizer *)pan{
    NSLog(@"dsd");
}
-(void)swipeGesture:(UISwipeGestureRecognizer *)swip{
    NSLog(@"dsd");
}
-(void)setUpToolBar{
    _toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0,60, self.view.frame.size.width,60)];
      UIBarButtonItem  *adjust = [[UIBarButtonItem alloc]initWithTitle:@"夜晚" style:UIBarButtonItemStylePlain target:self action:@selector(daytimeAndNight)];
    UIBarButtonItem  *previousPage = [[UIBarButtonItem alloc]initWithTitle:@"上一页" style:UIBarButtonItemStylePlain target:self action:@selector(previousPage)];
    UIBarButtonItem  *nextPage = [[UIBarButtonItem alloc]initWithTitle:@"下一页" style:UIBarButtonItemStylePlain target:self action:@selector(nextPage)];
    UIBarButtonItem* button =[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    NSArray *arr =@[previousPage,button,adjust,button,nextPage];
    _toolBar.items = arr;
    [_toolView addSubview:_toolBar];

}
-(void)daytimeAndNight{
    if ([_toolBar.items[2].title isEqualToString:@"夜晚"]) {
         _content.backgroundColor = [UIColor blackColor];
        _content.textColor = [UIColor whiteColor];
        _toolBar.items[2].title = @"白天";
    }else{
         _content.backgroundColor = [UIColor clearColor];
        _content.textColor = [UIColor redColor];
        _toolBar.items[2].title = @"夜晚";
    }
}
-(void)swipeGesture{
    UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)];
    swipe.direction=UISwipeGestureRecognizerDirectionLeft;
    [self.view addGestureRecognizer:swipe];
    UISwipeGestureRecognizer *swipe1 = [[UISwipeGestureRecognizer alloc]initWithTarget:self action:@selector(swipeAction:)];
    swipe1.direction=UISwipeGestureRecognizerDirectionRight;
    [self.view addGestureRecognizer:swipe1];
    
}

-(void)swipeAction:(UISwipeGestureRecognizer *)swipe{
    if (swipe.direction==UISwipeGestureRecognizerDirectionRight ) {
        [self previousPage];
    }else{
        [self nextPage];
    }
}
// 上一页
-(void)previousPage{
    if (_currentPage ==1) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"已经是第一页了" preferredStyle:UIAlertControllerStyleAlert];
        //点击按钮的响应事件；
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        //弹出提示框；
        [self presentViewController:alert animated:true completion:nil];
        return;
    }
    _currentPage = _currentPage-1;
    //上一页的定位
    [_content setContentOffset:CGPointMake(0, (_currentPage-1)*_content.frame.size.height) animated:YES];
      _sliderLabel.text =[NSString stringWithFormat:@"%d/%d",_currentPage,_allPage];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.view cache:NO];
    [UIView commitAnimations];
}
//下一页
-(void)nextPage{
    if (_currentPage ==_allPage) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"已经是最后一页了" preferredStyle:UIAlertControllerStyleAlert];
        //点击按钮的响应事件；
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        //弹出提示框；
        [self presentViewController:alert animated:true completion:nil];
        return;
    }
    _currentPage = _currentPage+1;
    //上一页的定位
    [_content setContentOffset:CGPointMake(0, (_currentPage-1)*_lengthPerPage) animated:YES];
      _sliderLabel.text =[NSString stringWithFormat:@"%d/%d",_currentPage,_allPage];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:1];
    [UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:self.view cache:NO];
    [UIView commitAnimations];
}
-(void)backToCell{
    //创建动画
    CATransition *animation = [CATransition animation];
    //设置运动轨迹的速度
    animation.timingFunction = UIViewAnimationCurveEaseInOut;
    //设置动画类型为立方体动画
    animation.type = @"oglFlip";
    //设置动画时长
    animation.duration =0.5f;
    //设置运动的方向
    animation.subtype =kCATransitionFromRight;
    //控制器间跳转动画
    [[UIApplication sharedApplication].keyWindow.layer addAnimation:animation forKey:nil];
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
